package com.root.dreameraadmin.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.root.dreameraadmin.R;
import com.root.dreameraadmin.adapter.Myadapter;
import com.root.dreameraadmin.adapter.PictureAdapter;
import com.root.dreameraadmin.utils.AsyncGetDataUtil;
import com.root.dreameraadmin.utils.HttpConnectionUtil;

import org.json.JSONException;
import org.w3c.dom.Text;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.root.dreameraadmin.view.ToolBarView.startIntroAnimation;


/**
 * Created by root on 16-6-27.
 */
public class PointActivity extends AppCompatActivity {

    @Nullable
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_text)
    TextView toolbar_textView;
    @Bind(R.id.ib_map)
    Button mapBtn;
    @Bind(R.id.piclistView)
    ListView picture_listview;
    @Bind(R.id.tip)
    TextView tipTextView;

    private static final String TAG = "PointActivity";
    private int point_id;
    private String point_name;
    private String point_longitude;
    private String point_latitude;

    ArrayList<HashMap<String,Object>> listItem;
    private String cross_pictures;
    Myadapter myadapter;
    private String item_id = "";
    private int position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.point_item);
        ButterKnife.bind(this);

        mapBtn.setVisibility(View.GONE);

        AsyncGetDataUtil.getDataFromServer(); //重新获取数据

        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        point_id = bundle.getInt("point_id");
        point_name = bundle.getString("name");
        point_longitude = bundle.getString("longitude");
        point_latitude = bundle.getString("latitude");
        cross_pictures = bundle.getString("cross_pictures");

        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, point_name);

        picture_listview = (ListView) findViewById(R.id.piclistView);

        try {
            Log.d(TAG,"cross_pictures  is " + cross_pictures);

            listItem = AsyncGetDataUtil.decodeCrossPicturesJsonToPoint(cross_pictures);//problem is here
            Log.d(TAG,"listItem is "+listItem);
            List<String> pic_id = new ArrayList<String>();
            List<String> URL = new ArrayList<String>();
            List<String> title = new ArrayList<String>();
            List<String> datetime = new ArrayList<String>();
            List<String> detail_title = new ArrayList<String>();

            if(listItem.size() == 0) {
                tipTextView.setVisibility(View.VISIBLE);
                tipTextView.setText("没有图片，点击右下方\"+\"按钮添加图片 ");
            } else {
                for (int i = 0; i < listItem.size(); i++) {
                    pic_id.add((String)listItem.get(i).get("id"));
                    URL.add((String) listItem.get(i).get("url"));
                    title.add((String) listItem.get(i).get("title"));
                    datetime.add((String)listItem.get(i).get("date"));
                    String detail = (String)listItem.get(i).get("detail_title");
                    System.out.println("asdf detail "+ detail);
                    if(detail.equals("") || detail == null || detail == "null"){
                        detail_title.add("空");
                    }else {
                        detail_title.add(detail);
                    }
                }
                Log.d(TAG,"the URL is"+URL);
                Log.d(TAG,"The title is"+title);

                PictureAdapter pictureAdapter = new PictureAdapter(
                        PointActivity.this, URL,
                        title, pic_id,
                        datetime, detail_title,
                        picture_listview
                );
                // 添加并显示
                picture_listview.setAdapter(pictureAdapter);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        picture_listview.setOnItemLongClickListener(itemLongClickListener);
        picture_listview.setOnItemClickListener(itemClickListener);

    }


    @OnClick(R.id.ib_back)
    public void clickBack() {
        finish();
    }

    @OnClick(R.id.ib_map)
    public void clickMap() {
        Intent intent = new Intent();
        intent.putExtra("point_name",point_name);
        intent.putExtra("point_longitude",point_longitude);
        intent.putExtra("point_latitude",point_latitude);
        intent.putExtra("point_id",point_id);
        intent.setClass(PointActivity.this, PointInMapActivity.class);
        PointActivity.this.startActivity(intent);
    }

    @OnClick(R.id.fab)
    public void clickAddPointBtn() {
        Intent intent = new Intent();
        intent.setClass(PointActivity.this, AddPictureActivity.class);
        intent.putExtra("point_id", point_id);
        PointActivity.this.startActivity(intent);
    }

    AdapterView.OnItemLongClickListener itemLongClickListener =
            new AdapterView.OnItemLongClickListener(){
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int item_position, long id) {
//            System.out.println("asdf item position " + item_position);
            HashMap<String, Object> item = listItem.get(item_position);
            item_id = (String) item.get("id");
            position = item_position;
            new AlertDialog.Builder(PointActivity.this)
                    .setMessage("要删除这个图片吗?")//设置显示的内容
                    .setPositiveButton("删除", positiveListener)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener(){//添加返回按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//响应事件
                            dialog.dismiss();
                        }
                    }).show();
            return true;
        }
    };

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            HashMap<String, Object> item = listItem.get(position);
            String pic_id = (String) item.get("id");
            String pic_title = (String) item.get("title");
            String picture = (String) item.get("picture");
            String datetime = (String) item.get("date");
            String time_str = (String) item.get("time_str");
            String detail_title = (String) item.get("detail_title");
            String url = (String) item.get("url");
            System.out.println("asdf url ");

            Intent intent = new Intent();
            intent.setClass(PointActivity.this, PictureActivity.class);
            intent.putExtra("point_id",point_id);
            intent.putExtra("title", pic_title);
            intent.putExtra("id", pic_id);
            Log.d(TAG, "picture id is" + pic_id);
            intent.putExtra("picture", picture);
            intent.putExtra("datetime", datetime);
            intent.putExtra("time_str", time_str);
            intent.putExtra("detail_title", detail_title);
            intent.putExtra("url", url);

            PointActivity.this.startActivity(intent);
        }
    };

    DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
            //new thread to delete
            new Thread(){
                public void run(){
                    try{
                        HttpConnectionUtil.doDelete(HttpConnectionUtil.PICTUREURl+item_id +"/");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(HttpConnectionUtil.result == "success"){
                                    Toast.makeText(PointActivity.this,"Delete is ok!",Toast.LENGTH_SHORT).show();
                                    listItem.remove(position);
                                    myadapter.notifyDataSetChanged();
                                    Log.d( TAG,"delete a picture" );
                                }
                            }
                        });
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    };

    @Override
    protected void onResume(){
        AsyncGetDataUtil.getDataFromServer(); //重新获取数据
        System.out.println("asdf here");
        super.onResume();
    }




}
